package com.xu.service;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xu.mapper.CollegeMapper;
import com.xu.mapper.UserMapper;
import com.xu.pojo.College;
import com.xu.pojo.User;
import com.xu.pojo.UserExcel;
import com.xu.utils.EncryptUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class UserServiceImpl implements UserService{

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private CollegeMapper collegeMapper;

    @Override
    public User queryUserByID(int id) {
        return userMapper.queryUserByID(id);
    }

    @Override
    public int updatePwd(int id, String pwd) {
        User user = userMapper.queryUserByID(id);
        String encryptPwd = EncryptUtil.encrypt(pwd, user.getSalt());
        return userMapper.updatePwd(id,encryptPwd);
    }

    @Override
    public List<User> queryUserByRole(String roles) {
        return userMapper.queryUserByRole(roles);
    }

    @Override
    public int addUser(User user) {
        //加密
        List<String> pwds = EncryptUtil.encrypt(user.getPassword());
        user.setPassword(pwds.get(0));
        user.setSalt(pwds.get(1));
        //设置id
        int id = userMapper.sortmaxId(user.getRoles())+1;
        user.setUserId(id);
        //添加用户
        userMapper.addUser(user);
        return 0;
    }

    @Override
    public int delteUser(int id) {
        return userMapper.delteUser(id);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public List<User> queryUserIf(String roles, String queryCondition, int collegeId) {
        return userMapper.queryUserByRoleIfIdNameCollege(roles,queryCondition,collegeId);
    }

    @Override
    public PageInfo<User> queryUserByRolePaging(String roles, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> lists = userMapper.queryUserByRole(roles);
        //System.out.println(lists);
        PageInfo<User> pageInfo = new PageInfo<User>(lists);
        return pageInfo;
    }

    @Override
    public PageInfo<User> queryUserIfPaging(String roles, String queryCondition, int collegeId, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<User> lists = userMapper.queryUserByRoleIfIdNameCollege(roles,queryCondition,collegeId);
        //System.out.println(lists);
        PageInfo<User> pageInfo = new PageInfo<User>(lists);
        return pageInfo;
    }

    @Override
    public String addMutiUser(MultipartFile file, String roles){
        InputStream inputStream = null;
        String result = null;
        try{
            inputStream = file.getInputStream();
            List<UserExcel> list =  new ArrayList<>();
            // EasyExcel 读取是基于SAX方式，因此在解析时需要传入监听器
            // 第一个参数为excel文件路径或inputstream
            // 第一个参数为读取时的数据类型
            // 第三个参数为监听器
            EasyExcel.read(inputStream, UserExcel.class, new AnalysisEventListener<UserExcel>() {
                // 每读取一行就调用该方法
                @Override
                public void invoke(UserExcel data, AnalysisContext context) {
                    list.add(data);
                }
                // 全部读取完成就调用该方法
                @Override
                public void doAfterAllAnalysed(AnalysisContext context) {
                    System.out.println("读取完成");
                }
            }).sheet().doRead();   //.sheet() 为空则默认读取第一个sheet
            //list.forEach(System.out::println);
            int successNum = transferList(list, roles);
            result="总数量："+list.size()+"----成功数量："+successNum;
        } catch (Exception e) {
            e.printStackTrace();
            result = "上传失败";
        }finally {
            //无论成功与否，都有关闭输入流
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return result;
        }
    }

    @Override
    public int transferList(List<UserExcel> list, String roles) {
        int result = 0;
        //设置id
        int id = userMapper.sortmaxId(roles);
        for (UserExcel userExcel:list) {
            User user = trans(userExcel, roles);
            if (user != null){
                user.setUserId(++id);
                userMapper.addUser(user);
                result++;
            }

        }
        return result;
    }

    @Override
    public User trans(UserExcel userExcel, String roles) {
        User user = new User();
        user.setUserName(userExcel.getName());
        user.setRoles(roles);
        //添加性别
        if (userExcel.getGender().equals("男"))
            user.setGender(0);
        else{
            if (userExcel.getGender().equals("女"))
                user.setGender(1);
            else
                return null;
        }
        //加密
        List<String> pwds = EncryptUtil.encrypt(userExcel.getPwd());
        user.setPassword(pwds.get(0));
        user.setSalt(pwds.get(1));
        //添加学院
        College college = collegeMapper.queryCollegeByName(userExcel.getCollegeName());
        if (college==null)
            return null;
        else
            user.setCollege(college);
        return user;
    }
}
